#!/usr/bin/env python  
# encoding: utf-8   

""" 
@version: v1.0 
@author: null 
@software: PyCharm 
@file: follow.py 
@time: 2017.4.29 20:45 
"""

from ..auth import need_login
from weibo.models import Model
from weibo.url import URL
import weibo.settings as config
import urllib
from bs4 import BeautifulSoup
import re
import simplejson as json
from selenium import webdriver
from weibo.utils import *
import time

class Follow(Model):
    def __init__(self,isProxy=False):
        super(Follow, self).__init__()
        print('follow')
        self.proxy = isProxy and config.proxy or {}
        pass

    @need_login
    def followAdd(self, *args, **kwargs):


        # followdata = {
        #     "uid": args[0],
        #     "st": self.st,
        # }
        #luicode = self.getLuicode()
        #param = urllib.parse.quote("罗永浩")
        # config.followHeaders["Referer"] = "http://m.weibo.cn/u/" + args[0] + "?uid=" + args[0] + "&luicode=" + luicode + "&lfid=100103type%3D1%26q%3D" + param
        # return self.post(URL.followadd(),followdata,config.followHeaders,proxy=self.proxy)

        url ="http://m.weibo.cn/u/" + args[0] #+ "?uid=" + args[0] + "&luicode=" + luicode + "&lfid=100103type%3D1%26q%3D" + param
        browser = webdriver.Chrome()
        browser.get("http://m.weibo.cn/cn/u"+str(args[0]))
        cookieStr = cookieObj2cookieStr(self.session.cookies)
        cookieDic = cookieStr2cookieDic(cookieStr)
        for k,v in cookieDic.items():
            browser.add_cookie({'name': k,'value':v})
        browser.get(url)

        time.sleep(1)
        try:
            followbtn = browser.find_element_by_class_name('m-add-box')
            followbtn.click()
        except:
            self.logger.error("关注异常")
            return "error"
        return "suc"
        pass

    @need_login
    def followDelete(self, *args, **kwargs):

        # response = self.session.get(url=URL.herblogsIndex(str(args[0])),headers=config.headers)
        #
        # print(response.text)
        #
        # followdata={
        #     "uid":args[0],
        #     "st":self.st
        # }
        # param = urllib.parse.quote("罗永浩")
        # luicode = self.getLuicode()
        # config.followHeaders["Referer"] = "http://m.weibo.cn/u/" + args[0] + "?uid=" + args[0] + "&luicode="+luicode+"&lfid=100103type%3D1%26q%3D" + param
        # return self.post(URL.followdelete(),followdata,config.followHeaders,proxy=self.proxy)

        url = "http://m.weibo.cn/u/" + args[0] #+ "?uid=" + args[0] + "&luicode=" + luicode + "&lfid=100103type%3D1%26q%3D" + param
        browser = webdriver.Chrome()
        browser.get("http://m.weibo.cn/cn/u" + str(args[0]))
        cookieStr = cookieObj2cookieStr(self.session.cookies)
        cookieDic = cookieStr2cookieDic(cookieStr)

        for k, v in cookieDic.items():
            browser.add_cookie({'name': k, 'value': v})
        browser.get(url)

        time.sleep(1)
        try:
            unfollowbtn = browser.find_element_by_xpath("//div[@class='m-diy-btn m-box-col m-box-center m-box-center-a'][1]//div[@class='m-pop m-pop-s']//li[2]//div[@class= 'm-diy-btn m-box-col m-box-center m-box-center-a']/h4")
            print(unfollowbtn)
            unfollowbtn.click()
            #cancelbtn = browser.find_element_by_partial_link_text("取消关注")
            #cancelbtn.click()
        except Exception as e:
            print(e)
            self.logger.error("取消关注异常")
            return "error"
        time.sleep(600)
        return "suc"

        pass

    def getLuicode(self):
        searchPage = self.session.get(url=URL.searchPage(), headers=config.headers,proxies=self.proxy).text
        soup = BeautifulSoup(searchPage, 'html.parser')
        script = soup.body.find_all("script")
        jsonstr = re.findall("{.+}", script[0].string.split(";")[1])[0].replace("'", "\"")
        jsonobj = json.loads(jsonstr)
        luicode = jsonobj.get("common").get("params").get("luicode")
        return luicode

        pass
